﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Dhtl.Service.IService;
using dai_hoc_tuong_lai.Areas.Admin.Models;
using DataBase.Daihoctuonglai;
using FarmeWork.Helper;
using Comom.Project.ControllerCom;
using Comom.Project.JsonCom;

namespace dai_hoc_tuong_lai.Areas.Admin.Controllers
{
    
    public class UserController : UTController
    {
        //
        // GET: /Admin/User/
         private readonly IRoles _iRoles;
         private readonly IUser _iUser;
         private readonly IUserInRoles _iUserInRoles;
         private readonly EncryptPass mahoa = new EncryptPass();

         public UserController(IRoles iRoles, IUser iUser, IUserInRoles iUserInRoles)
        {
            this._iRoles = iRoles;
            this._iUser = iUser;
            this._iUserInRoles = iUserInRoles;
        }

        [Authorize(Roles = "Admin")]
        public ActionResult Index()
        {
            var c = new List<Role>();
            c.Add(new Role { Id = 0 , Name = "[None]" });

            var gh = _iRoles.List().ToList();

            if (c.Count() > 0)
            {
                foreach (var g in gh)
                {
                    c.Add(g);
                }
            }

            ViewData["ListRoles"] = new SelectList(c, "Id", "Name");

            return View();
        }

        [Authorize(Roles = "Admin")]
        public ActionResult IndexDaily()
        {
            var c = new List<Role>();
            c.Add(new Role { Id = 0, Name = "[None]" });

            var gh = _iRoles.List().ToList();

            if (c.Count() > 0)
            {
                foreach (var g in gh)
                {
                    c.Add(g);
                }
            }

            ViewData["ListRoles"] = new SelectList(c, "Id", "Name");

            return View();
        }

        [Authorize(Roles = "Admin")]
        public ActionResult List()
        {

            var listEntity = _iUser.List();
            List<UserModel> model = new List<UserModel>();
            try
            {
                foreach (var item in listEntity)
                {
                    UserModel ml = new UserModel();
                    UserModel.MapFrom(item, ref  ml);
                    model.Add(ml);
                }
            }
            catch { }

            return PartialView("_List", model);
        }

        [Authorize(Roles = "Admin,Quanlydaily")]
        public ActionResult Add()
        {
            UserModel model = new UserModel();
            model.Id = 0;
         
            var gh = _iRoles.List();

            model.ModelCheck = new List<MoreInfoRoles>();
            if (gh.Count() > 0)
            {
                foreach (var item in gh)
                {
                    MoreInfoRoles itemCheck = new MoreInfoRoles()
                    {
                        Id = item.Id,
                        Name = item.Name,
                        Checkbox = false
                    };

                    model.ModelCheck.Add(itemCheck);
                }
            }

            return PartialView("_Add", model);
        }

        [Authorize(Roles = "Admin,Quanlydaily")]
        public ActionResult Update(int id)
        {
            UserModel model = new UserModel();
            var entity = _iUser.GetById(id);
            try
            {
                UserModel.MapFrom(entity, ref model);

                var gh = _iRoles.List();

                model.ModelCheck = new List<MoreInfoRoles>();

                if (gh.Count() > 0)
                {
                    foreach (var item in gh)
                    {
                        MoreInfoRoles itemCheck = new MoreInfoRoles()
                        {
                            Id = item.Id,
                            Name = item.Name,
                            Checkbox = _iUserInRoles.checkExitsRolesiD(entity.Id, item.Id),
                        };

                        model.ModelCheck.Add(itemCheck);
                    }
                }

                model.Pass = mahoa.Decrypt(model.Pass, "dailyphuthinh", true);

            }
            catch { }

            return PartialView("_Update", model);
        }

        [Authorize(Roles = "Admin,Quanlydaily")]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddOrUpdate(UserModel model)
        {

            try
            {
                if (string.IsNullOrEmpty(model.Name))
                {
                    return JsonError("Nhập tên user vào");
                }

                if (string.IsNullOrEmpty(model.Email))
                {
                    return JsonError("Nhập email user vào");
                }

                if (!IsValidEmailAddress(model.Email))
                {
                    return JsonError("Nhập email user sai định dạng vào");
                }

                if (!string.IsNullOrEmpty(model.EmailNew))
                {
                    var c = _iUser.GetByEmail(model.EmailNew);
                    if (c != null)
                    {
                        return JsonError(" Email thay đổi đã tồn tại, vui lòng kiểm tra lại");
                    }

                    if (!IsValidEmailAddress(model.EmailNew))
                    {
                        return JsonError("Email thay đổi sai định dạng");
                    }

                    model.Email = model.EmailNew;
                }

                if (string.IsNullOrEmpty(model.Pass))
                {
                    return JsonError("Nhập password user vào");
                }

                if (!string.IsNullOrEmpty(model.PassNew))
                {
                    model.Pass = model.PassNew;
                }

                model.Pass = mahoa.Encrypt(model.Pass, "dailyphuthinh", true);

                var entity = new Usser();
                UserModel.MapFrom(model, ref entity);
                int idUs = _iUser.addOrupdate(entity);


                if (model.Id > 0)
                {

                    foreach (var g in model.ModelCheck)
                    {
                        if (g.Checkbox == true)
                        {
                            if (!_iUserInRoles.checkExitsRolesiD(idUs, g.Id))
                            {
                                UserInRole userInRo = new UserInRole();
                                userInRo.Id = 0;
                                userInRo.UserId = idUs;
                                userInRo.RolesId = g.Id;
                                _iUserInRoles.AddOrUpdate(userInRo);
                            }
                        }
                        else
                        {
                            if (_iUserInRoles.checkExitsRolesiD(idUs, g.Id))
                            {
                                _iUserInRoles.removeRolesInUsser(idUs, g.Id);
                            }
                        }
                    }
                }
                else
                {
                    foreach (var g in model.ModelCheck)
                    {
                        if (g.Checkbox == true)
                        {
                            if (!_iUserInRoles.checkExitsRolesiD(idUs, g.Id))
                            {
                                UserInRole userInRo = new UserInRole();
                                userInRo.Id = 0;
                                userInRo.UserId = idUs;
                                userInRo.RolesId = g.Id;
                                _iUserInRoles.AddOrUpdate(userInRo);
                            }
                        }
                    }
                }
               return JsonSuccess(Url.Action("Index"), null);
            }
            catch (Exception ex)
            {
                return JsonError(ex.ToString());
            }
        }

       [Authorize(Roles = "Admin,Quanlydaily")]
        public ActionResult Delete(int id, int type)
        {
            try
            {
                _iUser.delete(id);
                if (type == 1)
                {
                    return JsonSuccess(Url.Action("Index"), null);
                }
                else
                {
                    return JsonSuccess(Url.Action("IndexDaily"), null);
                }
            }
            catch (Exception ex)
            {
                return JsonError(ex.ToString());
            }
        }

    }
}
